module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage6.Stage6HomeGui".new()
local wEasing = require "wEasing"

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
		local group = self.view
end




-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	-----------------------------------------------------------------------------
	local mainGroup = self.view

-----------------------------------------------------------------------------
	local backgroundGroup,stageButtonGroup,homeButtonGroup,generateItemsGroup
	local bg,replayButton,leftButton,centerButton,rightButton
	local okImage,goodImage,perfectImage
	
	local manageTotalTimer,totalTimer,totalTime
	
	local readyText,goText
	
	local itemEachTurn
	local deltaRunTime,deltaTouchTime
	local deltaTotalTime
	local _deltaRunTime,_deltaTouchTime = deltaRunTime,deltaTouchTime
	
	local imageButtons,imageItems = {},{}
	local temp1Position,temp2Position,temp3Position,tempPosition
	
	local existingButton,existingImage = nil,nil
	local backgroundButton = {}
	local countDownItems = {}
	local _scoreText = {}
	local _tran
	local timeScore = {}
	local countTimes = 0
	
	local tFomer
	local isTouchOk = true
	local _gameOver
	local _score = {6,7,8,9,10}
	local tStartTran = 0
	local tToTran = 0
	local instance,spriteText,actionText
	local _count
	
itemEachTurn = 3
	
function init()
	count = 0
	pauseButton.isVisible = true
	replayButton.isVisible = true
	-- okImage.alpha = 0
	-- goodImage.alpha = 0
	-- perfectImage.alpha = 0
	_gameOver.alpha = 0
	scoreText.alpha = 0
	countDownItems = {0,0,0,0,0,0}
	deltaRunTime = 000
	deltaTouchTime = 3000
	totalTime =  2000*itemEachTurn + 500 + deltaTouchTime + deltaRunTime
	deltaTotalTime = deltaRunTime
	
	totalTimer = timer.performWithDelay(100,manageTotalTimer,0)
end
	
--------------------------- create group -------------------------------
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
-----------------------------------

----------------------handle function ----------------------
function manageTotalTimer()
	deltaTotalTime = deltaTotalTime - 100
	if(deltaTotalTime >= 0)then
		readyText.alpha = 1
		readyText.text = math.round(deltaTotalTime/1000)
	elseif(deltaTotalTime <0 and deltaTotalTime >= -1000) then
		perfectImage.alpha = 0
		goodImage.alpha = 0
		okImage.alpha = 0
		readyText.alpha = 0
		goText.alpha = 1
		goText.text = "Go"
		if(existingButton ~= true)then
			existingButton = generateButton()
		end
	
	elseif(deltaTotalTime < -1000 and deltaTotalTime >= -1300*itemEachTurn - 500)then
		goText.alpha = 0
		if(existingImage ~= true)then
			existingImage = generateImage(itemEachTurn)
		end
		
	elseif(deltaTotalTime < -1300*itemEachTurn - 500 and deltaTotalTime >= -1300*itemEachTurn - 500 - deltaTouchTime)then
		-- print("touch")
		-- goText.text = "Touch"
		-- if(goText.alpha == 0)then
			-- goText.alpha = 1
		-- else goText.alpha = 0
		-- end
		spriteText.text = "Round "..(countTimes+1)
		count = count + 100
		if(count < 800)then
			instance.alpha = 1
			spriteText.alpha = 1
			actionText.alpha = 1
		else
			instance.alpha = 0
			actionText.alpha = 0
			spriteText.alpha = 0
		end
	elseif(deltaTotalTime < -1300*itemEachTurn - 500 - deltaTouchTime)then
		
		goText.alpha = 0
		instance.alpha = 0
		actionText.alpha = 0
		timer.cancel(totalTimer)
		for k,v in pairs(imageItems)do
			v = nil
		end
		for k,v in pairs(imageButtons) do
			v = nil
		end
		existingImage = false
		existingButton = false
		if(checkWinTurn(countDownItems))then
			countTimes = countTimes + 1
			-- print(countTimes)
			timeScore[countTimes] = system.getTimer() - tFomer
			showImageResult(timeScore[countTimes])
			scoreText.text = countTimes .." PTS"
			scoreText.alpha = 1
			local _tempTime = 1000
			local _tempTimer
			_tempTimer = timer.performWithDelay(100,function()
						_tempTime = _tempTime - 100
						if(_tempTime < 0)then
							-- scoreText.alpha = 0
							if(itemEachTurn < 6)then
								itemEachTurn = itemEachTurn + 1
							end
							if(countTimes < 10)then
								init()
							else
								pauseButton.isVisible = false
								finishedGame()
							end
						end
					end,0)			
		else
			gameOver()
		end
	end
end

------------------ helper function -----------------------

local exceptRandom = function(startNumber,endNumber,exceptNumber)
	local temp = {}
	local j = 0
	for i = 1,endNumber-startNumber+1,1 do
		j = j+1
		if(startNumber+i-1 ~= exceptNumber) then 
			temp[j] = startNumber + i -1
		else
			j = j - 1 
		end
	end
	_temp = math.random(1,endNumber - startNumber)
	return temp[_temp]
end

function checkWinTurn(countDownItems)
	local flag = true
	for k,v in pairs(countDownItems)do
		if(v ~= 0) then flag = false end
	end
	return flag
end

function generateButton()
	temp1Position = math.random(1,6)
	imageButtons[1] = display.newImageRect(stageButtonGroup,gui.image[temp1Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[1].x = gui.buttonPosition.x[1]
		imageButtons[1].y = gui.buttonPosition.y[1]
		imageButtons[1].id = temp1Position
	imageButtons[1]:addEventListener("tap",onMoveButtonTap)
		
	temp2Position = exceptRandom(1,6,temp1Position)
	imageButtons[2] = display.newImageRect(stageButtonGroup,gui.image[temp2Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[2].x = gui.buttonPosition.x[2]
		imageButtons[2].y = gui.buttonPosition.y[2]
		imageButtons[2].id = temp2Position
	imageButtons[2]:addEventListener("tap",onMoveButtonTap)
	
	temp3Position = 1
	while (temp3Position == temp1Position or temp3Position == temp2Position) do
		temp3Position = math.random(1,6)
	end
	imageButtons[3] = display.newImageRect(stageButtonGroup,gui.image[temp3Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[3].x = gui.buttonPosition.x[3]
		imageButtons[3].y = gui.buttonPosition.y[3]
		imageButtons[3].id = temp3Position
		imageButtons[3]:addEventListener("tap",onMoveButtonTap)
	return true
end

function onMoveButtonTap(event)
	local t = event.target
	if(isTouchOk == false) then
		for k,v in pairs(imageButtons) do
			v:removeEventListener("tap",onMoveButtonTap)
		end
		if(_tran ~= nil) then 
			transition.cancel(_tran)
		end
		gameOver()
		return
	end
	
	countDownItems[tonumber(t.id)] = countDownItems[tonumber(t.id)] - 1
	print(t.id," = ",countDownItems[tonumber(t.id)])
	if(checkWinTurn(countDownItems)) then
		countTimes = countTimes + 1
		-- print(countTimes)
		goText.alpha = 0
		readyText.alpha = 0
		timer.cancel(totalTimer)
		for k,v in pairs(imageButtons) do
			v:removeEventListener("tap",onMoveButtonTap)
		end
		for k,v in pairs(imageItems) do
			display.remove(v)
		end
		existingImage = false
		existingButton = false
		timeScore[countTimes] = system.getTimer() - tFormer
		scoreText.text = countTimes .." PTS"
		scoreText.alpha = 1
		showImageResult(timeScore[countTimes])
		local _tempTime = 1000
		local _tempTimer
		_tempTimer = timer.performWithDelay(100,function()
						_tempTime = _tempTime - 100
						if(_tempTime <= 0)then
							okImage.alpha = 0
							goodImage.alpha = 0
							perfectImage.alpha = 0
							timer.cancel(_tempTimer)
							if(_tran ~= nil) then 
								transition.cancel(_tran)
							end
							if(itemEachTurn < 6)then
								itemEachTurn = itemEachTurn + 1
							end
							if(countTimes < 10)then
								init()
							else
								finishedGame()
							end
						end
					end,0)
	end
	
end

function onReplayButtonTap()
	goText.alpha = 0
	scoreText.text = "0 PTS"
	scoreText.alpha = 0
	itemEachTurn = 3
	countTimes = 0
	if(totalTimer)then
		timer.cancel(totalTimer)
	end
	existingButton = false
	existingImage = false
	for k,v in pairs(imageButtons)do
		v:removeEventListener("tap",onMoveButtonTap)
		display.remove(v)
	end
	for k,v in pairs(imageItems)do
		display.remove(v)
	end
	if(_tran)then
		transition.cancel(_tran)
	end
	init()
end

function generateImage(itemEachTurn)
	imageItems[1] = display.newImageRect(generateItemsGroup, gui.food[temp1Position].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[1].x = 1*gui.displayWidth/4
		imageItems[1].y = 265
		imageItems[1].id = temp1Position
	
	imageItems[2] = display.newImageRect(generateItemsGroup, gui.food[temp2Position].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[2].x = 2*gui.displayWidth/4+15
		imageItems[2].y = 265
		imageItems[2].id = temp2Position
		
	for i = 3,itemEachTurn,1 do
		tempPosition = math.random(1,6)
		imageItems[i] = display.newImageRect(generateItemsGroup, gui.food[tempPosition].fn, gui.buttonPosition.w*0.9, gui.buttonPosition.h*0.9)
		imageItems[i].x = i*gui.displayWidth/4+15*(i-1)
		imageItems[i].y = 265
		imageItems[i].id = tempPosition
	end
	
	local i
	for i=1,6,1 do
		countDownItems[i] = 0
	end
	for k,v in pairs(imageButtons) do
		for k1,v1 in pairs(imageItems) do
			if (v.id == v1.id) then
				countDownItems[tonumber(v.id)] = countDownItems[tonumber(v.id)] + 1
			end
		end
	end
	----------------------- for test ---------------------
	-- for k,v in pairs(_scoreText) do
		-- display.remove(v)
	-- end
	-- for k,v in pairs(imageButtons)do
		-- _scoreText[k] = display.newText(countDownItems[tonumber(v.id)],v.x+50, v.y - 50,native.systemFontBold,18)
		-- _scoreText[k]:setTextColor(255,0,0)
	-- end
	---------------------------------------------------------
	generateItemsGroup.x =  -1 * (itemEachTurn /4)*gui.displayWidth
	tStartTran = system.getTimer()
	tToTran = itemEachTurn*1300
	_tran = transition.to(generateItemsGroup,{time = itemEachTurn * 1300, alpha = 1, 
	x = gui.displayWidth-30, y = generateItemsGroup.y, 
	onStart = onStartGenerateItems, onComplete = onFinishGenerateItems })
	return true
end

function onStartGenerateItems()
	isTouchOk = false
end

function onFinishGenerateItems()
	isTouchOk = true
	tFormer = system.getTimer()
end

function showImageResult(deltaTime)
	if(deltaTime >= 0 and deltaTime < 1000)then
		perfectImage.alpha = 1
		goodImage.alpha = 0
		okImage.alpha = 0
	elseif(deltaTime >= 1000 and deltaTime < 2000)then
		perfectImage.alpha = 0
		goodImage.alpha = 1
		okImage.alpha = 0
	elseif(deltaTime >= 2000)then
		perfectImage.alpha = 0
		goodImage.alpha = 0
		okImage.alpha = 1
	end
end

function finishedGame()
	-- for k,v in pairs(timeScore) do
		-- print(v)
	-- end
	local temp = (countTimes - 5)
	local g1
	if(temp < 0)then
		g1 = require "popup.popupWin".new(countTimes,0,_score,onReplayButtonTap)
	else
		g1 = require "popup.popupWin".new(countTimes,temp,_score,onReplayButtonTap)
	end
	transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
end

function onStartPopup()
	timer.pause(totalTimer)
	if(_tran ~= nil)then
		transition.cancel(_tran)
	end	
	tToTran = tToTran - (system.getTimer() - tStartTran)
	-- for k,v in pairs(generateItemsGroup)do
		-- v.alpha = 0
	-- end
end

function onResumeFromPopup()
	timer.resume(totalTimer)
	-- for k,v in pairs(generateItemsGroup)do
		-- v.alpha = 1
	-- end
	if(_tran ~= nil)then
		transition.to(generateItemsGroup,{time = tToTran, alpha = 1, 
	x = gui.displayWidth-30, y = generateItemsGroup.y, 
	onStart = onStartGenerateItems, onComplete = onFinishGenerateItems})
	end
end

function gameOver()
	if(_tran ~= nil) then
		transition.cancel(_tran)
	end
	for k,v in pairs(imageItems)do
		display.remove(v)
		table.remove(imageItems,k)
	end
	for k,v in pairs(imageButtons)do
		v:removeEventListener("tap",onMoveButtonTap)
	end
	if(totalTimer ~= nil)then
		timer.cancel(totalTimer)
	end
	pauseButton.isVisible = false
	replayButton.isVisible = false
	-- _gameOver.alpha = 1
	local temp = (countTimes - 5)
	-- print(temp)
	local g1
	if(temp < 0)then
		g1 = require "popup.popupWin".new(countTimes,0,_score,onReplayButtonTap)
	else
		g1 = require "popup.popupWin".new(countTimes,temp,_score,onReplayButtonTap)
	end
	transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
end

do ------------------------------- score -------------------
scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	scoreText.alpha = 0
homeButtonGroup:insert(scoreText)

_gameOver = display.newText(homeButtonGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	_gameOver.x = display.contentCenterX
	_gameOver.y = display.contentCenterY
	_gameOver:setTextColor(unpack(gui.score.color))
	_gameOver.alpha = 0
end
do -------------------- background and button ---------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})
pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup })
		-- backgroundGroup:insert(group2)
	end
})

backgroundButton[1] = display.newImageRect(stageButtonGroup,gui.leftButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[1].x = gui.buttonPosition.x[1]
	backgroundButton[1].y = gui.buttonPosition.y[1]
	backgroundButton[1].alpha = 0
backgroundButton[2] = display.newImageRect(stageButtonGroup,gui.centerButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[2].x = gui.buttonPosition.x[2]
	backgroundButton[2].y = gui.buttonPosition.y[2]
	backgroundButton[2].alpha = 0
backgroundButton[3] = display.newImageRect(stageButtonGroup,gui.rightButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[3].x = gui.buttonPosition.x[3]
	backgroundButton[3].y = gui.buttonPosition.y[3]
	backgroundButton[3].alpha = 0
end
do ---------------- image result ----------------------
okImage = display.newImageRect(homeButtonGroup,gui.okImage.fn,gui.okImage.w,gui.okImage.h)
	okImage.x = gui.okImage.x
	okImage.y = gui.okImage.y
	okImage.alpha = 0

goodImage = display.newImageRect(homeButtonGroup,gui.goodImage.fn,gui.goodImage.w,gui.goodImage.h)
	goodImage.x = gui.goodImage.x
	goodImage.y = gui.goodImage.y
	goodImage.alpha = 0

perfectImage = display.newImageRect(homeButtonGroup,gui.perfectImage.fn,gui.perfectImage.w,gui.perfectImage.h)
	perfectImage.x = gui.perfectImage.x
	perfectImage.y = gui.perfectImage.y
	perfectImage.alpha = 0
end

local sheet1 = graphics.newImageSheet( gui.action.fn, { width=gui.action.w, height=gui.action.h, numFrames=1 } )
	instance = display.newSprite( sheet1, { name = "action", start=1, count=1, time=1000 } )
	instance.x = gui.action.x
	instance.y = gui.action.y
	instance.xScale = 0.5
	instance.yScale = 0.5
	instance:play()
	instance.alpha = 0
stageButtonGroup:insert(instance)

mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(homeButtonGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(pauseButton)
mainGroup:insert(replayButton)

------------------------------------ text -----------------
readyText = display.newText(mainGroup, "2",160 , 150, gui.timer.font, gui.timer.fontSize+20)
	readyText:setTextColor(255,0,0)
	readyText.alpha = 0
-- goText = display.newText(mainGroup, "Action", 160 -30, 150, gui.timer.font, gui.timer.fontSize+20)
	-- goText:setTextColor(255,0,0)
	-- goText.alpha = 0
goText = display.newImageRect(mainGroup,gui.goImage.fn,gui.goImage.w,gui.goImage.h)
	goText.x = gui.goImage.x
	goText.y = gui.goImage.y
	goText.alpha = 0

spriteText = display.newText(mainGroup,"Round", 95,260,native.systemFontItalic,gui.timer.fontSize + 2)
	spriteText:setTextColor(255,0,0)
	spriteText.alpha = 0
-- actionText = display.newText(mainGroup,"Action", 20,50,native.systemFontBold,gui.timer.fontSize + 20)
	-- actionText:setTextColor(255,0,0)
	-- actionText.rotation = -20
	-- actionText.alpha = 0

actionText = display.newImageRect(mainGroup,gui.actionImage.fn,gui.actionImage.w,gui.actionImage.h)
	actionText.x = gui.actionImage.x
	actionText.y = gui.actionImage.y
	actionText.rotation = gui.actionImage.r
	actionText.alpha = 0

------------------------------------- run test --------------------------------------
init()

----------------------------- end run test ------------------------------------------------



	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene